package com.boardgame.gwt.controller;

import cloud.common.redis.redis.service.IRedisService;
import com.boardgame.common.entity.ResponseInfo;
import com.boardgame.gwt.common.GameInitial;
import com.boardgame.gwt.data.GwtGameBoard;
import com.boardgame.gwt.entity.GwtGameDbInfo;
import com.boardgame.gwt.service.operate.SyntaxRegex;
import com.boardgame.gwt.service.operate.SyntaxRequest;
import com.boardgame.gwt.repository.GwtGameInfoRepository;
import com.boardgame.gwt.repository.GwtPlayerRepository;
import com.boardgame.gwt.service.GwtGameInfoService;
import com.boardgame.users.service.PlayerInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.regex.Matcher;

/**
 * Created by pdybka on 13.06.16.
 */

@RestController
@RequestMapping("/gwtgame")
public class GwtGameController {

    /**
     * 游戏信息
     */
    @Autowired
    private GwtGameInfoRepository gwtGameInfoRepository;
    @Autowired
    GwtGameInfoService gameService;
    @Autowired
    PlayerInfoService playerService;
    @Autowired
    HttpSession httpSession;
    Logger logger = LoggerFactory.getLogger(GwtGameController.class);

    /**
     * 游戏玩家信息
     */
    @Autowired
    private GwtPlayerRepository gwtPlayerRepository;
    /**
     * redis
     */
    @Autowired(required = false)
    @Qualifier("redisServiceImpl")
    private IRedisService iRedisService;
    /**
     * 新建游戏
     * @param gameDTO
     * @return
     */
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public ResponseInfo<GwtGameDbInfo> createNewGame(@RequestBody GwtGameDbInfo gameDTO) {
        if (gwtGameInfoRepository.existsGwtGameInfoByGameName(gameDTO.getGameName())){
            return ResponseInfo.Failed("game existed");
        }
        //playerService.getLoggedUser()
        GwtGameDbInfo game = gameService.createNewGame( null,gameDTO);
        httpSession.setAttribute("gameName", game.getGameName());
        logger.info("new game id: " + httpSession.getAttribute("gameId")+ " stored in session" );
        //保存到redis游戏
        GwtGameBoard gwtGameBoard = GameInitial.create(game,this.gwtPlayerRepository);
        gwtGameBoard.saveToRedis(this.iRedisService);

        return ResponseInfo.Success(game);
    }

    private ResponseInfo responseInfo;
    /**
     * 发送游戏命令
     * @return
     */
    @RequestMapping(value = "/syntax", method = RequestMethod.POST)
    public ResponseInfo syntax(@RequestBody SyntaxRequest gameSyntax) {
        //获取游戏
        GwtGameBoard gwtGameBoard = this.getGameProperties(gameSyntax.getGameName());
        if (gwtGameBoard==null){
            return ResponseInfo.Failed("游戏不存在");
        }
        else if (!gwtGameBoard.getCurrentPlayer().getUserName().equals(gameSyntax.getUserName())){
            return ResponseInfo.Failed("不是当前玩家回合");
        }
        //执行命令
        SyntaxRegex.listSyntax.forEach(action->{
            Matcher matcher = action.getPattern().matcher(gameSyntax.getSyntax());
            if (matcher.find()){
                this.responseInfo = action.action(gwtGameBoard,gameSyntax,matcher);
                if (this.responseInfo.getStatus()!=200){
                    return;
                }
                //gwtGameBoard.setNextPlayer();
                action.saveToRedis(iRedisService);

            };
        });
        return this.responseInfo;
    }

    @RequestMapping(value = "/list", produces = MediaType.APPLICATION_JSON_VALUE)
    public List<GwtGameDbInfo> getGamesToJoin() {
        List<GwtGameDbInfo> list = gwtGameInfoRepository.findAll();
        return list;
        //return gameService.getGamesToJoin(playerService.getLoggedUser());
    }

    @RequestMapping(value = "/join", method = RequestMethod.POST)
    public GwtGameDbInfo joinGame(@RequestBody GwtGameDbInfo gameDTO) {
        //GwtPlayer gwtPlayer = new GwtPlayer();
        //playerService.getLoggedUser()
        //GwtGameInfo game = gameService.joinGame(this.gameService.createGwtPlayer("ala","yellow"), gameDTO);
        return null;
    }

    @RequestMapping(value = "/player/list", produces = MediaType.APPLICATION_JSON_VALUE)
    public List<GwtGameDbInfo> getPlayerGames() {
        return null;
        //return gameService.getPlayerGames(playerService.getLoggedUser());
    }

    /**
     * 根据游戏名称来获取游戏
     * 从redis获取游戏
     * @param gameName
     * @return
     */
    @RequestMapping(value = "/{gameName}")
    public GwtGameBoard getGameProperties(@PathVariable String gameName) {
        httpSession.setAttribute("gameName", gameName);
        //从redis获取游戏
        GwtGameBoard  gameBoard = (GwtGameBoard)this.iRedisService.getValue(gameName,false);
        System.out.println("获取游戏:"+gameName+gameBoard!=null);
        //gameBoard.setListActionSyntax(SyntaxRegex.listSyntax);
        return gameBoard;//gameService.getGameByname(gameName);
    }

}
